using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;
using System.Runtime.Remoting.Contexts;
using Microsoft.SharePoint.Navigation;
using System.Web;
using System.Diagnostics;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using Microsoft.SharePoint.Publishing;
using System.Collections.Generic;
using Microsoft.Office.Server.UserProfiles;


namespace eGov.SharePoint.MyPeeps.Features.MySiteHostCustomization
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("01dfb6c0-9081-45dc-8515-e273128d58fb")]
    public class MySiteHostCustomizationEventReceiver : SPFeatureReceiver
    {
        #region ULS Prep

        private SPDiagnosticsArea logArea;
        private SPDiagnosticsService logService = SPDiagnosticsService.Local;
        protected SPDiagnosticsArea LogArea
        {
            get
            {
                if (this.logArea == null)
                    this.logArea = new SPDiagnosticsArea("eGov.SharePoint.MyPeeps", new List<SPDiagnosticsCategory>
                    { 
                        new SPDiagnosticsCategory("MySiteHostCustomizationEventReceiver", TraceSeverity.High, EventSeverity.Error),
                        new SPDiagnosticsCategory("MySiteHostCustomizationEventReceiver", TraceSeverity.Verbose, EventSeverity.Information) 
                    });
                return this.logArea;
            }
        }
        protected SPDiagnosticsCategory logCategory_Error
        {
            // Indexing if used starts from 1
            get { return this.LogArea.Categories[1]; }
        }
        protected SPDiagnosticsCategory logCategory_Information
        {
            // Indexing if used starts from 1
            get { return this.LogArea.Categories[2]; }
        }

        #endregion

        private string KEY_CHK = Properties.Settings.Default.PartCheckKey;

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //SPSite site = properties.Feature.Parent as SPSite;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite mySiteHost = properties.Feature.Parent as SPSite;

                //using (SPSite mySiteHost = new SPSite(site.ID))
                //{
                SPWeb currentWeb = mySiteHost.OpenWeb();
                EventLog eventlog = new EventLog();
                eventlog.Source = "MySiteHost Customization Feature - Activation";

                try
                {

                    if (currentWeb.WebTemplate == "SPSMSITEHOST")
                    {
                        eventlog.WriteEntry("Starting Activation of the MySiteHost Customization Feature: SiteUrl:" + currentWeb.Url);

                        mySiteHost.AllowUnsafeUpdates = true;
                        currentWeb.AllowUnsafeUpdates = true;
           
                        SPFile customPersonAspx = currentWeb.GetFile("CustomPerson.aspx");

                        //Replace person.aspx with our custom file
                        SPFile personaspx = currentWeb.Files.Add("Person.aspx", customPersonAspx.OpenBinary(), true);
                        //Make sure part check Key does not exist - so that 'Follow me' webpart is added to person.aspx 
                        if (personaspx.Properties[KEY_CHK] != null)
                            personaspx.Properties[KEY_CHK] = null;
                        personaspx.Update();

                        //Add My Peeps Link to Global Navigatio
                        //When created navigation node verifies the url, throws exception if url cannot be resolved/reached
                        bool linkExists = false;
                        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(currentWeb);
                        for (int i = 0; i < publishingWeb.Navigation.GlobalNavigationNodes.Count; i++)
                        {
                            if (publishingWeb.Navigation.GlobalNavigationNodes[i].Title == Properties.Settings.Default.MYPeepsLinkTitle)
                            {
                                linkExists = true;
                                break;
                            }
                        }
                        if (!linkExists)
                        {
                            SPNavigationNode navNode = new SPNavigationNode(Properties.Settings.Default.MYPeepsLinkTitle, Properties.Settings.Default.MyPeepsLinkUrl);
                            publishingWeb.Navigation.GlobalNavigationNodes.AddAsLast(navNode);
                        }

                        eventlog.WriteEntry("Successfull Activation of the MySiteHost Customization Feature: SiteUrl:" + currentWeb.Url);

                        logService.WriteTrace(100, logCategory_Information, TraceSeverity.Verbose, "Feature activated.", null);
                    }
                }
                catch (Exception e)
                {
                    logService.WriteTrace(100, logCategory_Error, TraceSeverity.High,
                        String.Format("Feature failed on activation. Exception message: {0} \r\n Stack Trace: \r\n {1}", new object[] { e.Message, e.StackTrace }), null);

                    eventlog.WriteEntry(String.Format("Error activating MySite Host Customization feature {0}: SiteUrl:" + currentWeb.Url, e.ToString()), EventLogEntryType.Error);
                }
                finally
                {
                    currentWeb.Update();
                    mySiteHost.AllowUnsafeUpdates = false;
                    currentWeb.AllowUnsafeUpdates = false;
                }

                // }

            });
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite mySiteHost = properties.Feature.Parent as SPSite;
            SPWeb currentWeb = mySiteHost.OpenWeb();
            EventLog eventlog = new EventLog();
            eventlog.Source = "MySite Host Customization Feature - Deactivation";

            //SPSite site = properties.Feature.Parent as SPSite;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                //using (SPSite mySiteHost = new SPSite(site.ID))
                //{
                currentWeb.AllowUnsafeUpdates = true;
                mySiteHost.AllowUnsafeUpdates = true;
                try
                {

                    #region Retract feature Assets

                    if (currentWeb.WebTemplate == "SPSMSITEHOST")
                    {
                        eventlog.WriteEntry("Starting De-Activation of the MySiteHost Customization Feature: SiteUrl:" + currentWeb.Url);

                        #region Delete My Peeps Navigation Link
                        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(currentWeb);
                        for (int i = 0; i < publishingWeb.Navigation.GlobalNavigationNodes.Count; i++)
                        {
                            if (publishingWeb.Navigation.GlobalNavigationNodes[i].Title == Properties.Settings.Default.MYPeepsLinkTitle)
                            {
                                publishingWeb.Navigation.GlobalNavigationNodes[i].Delete();
                                publishingWeb.Update();
                                //break;
                            }
                        }
                        #endregion

                        //Reset person.aspx to its original version
                        SPFile originalPersonAspx = currentWeb.GetFile("BackupOfPerson.aspx");
                        SPFile personAspx = currentWeb.Files.Add("person.aspx", originalPersonAspx.OpenBinary(), true);
                        if (personAspx.Properties[KEY_CHK] != null)
                            personAspx.Properties[KEY_CHK] = null;
                        personAspx.Update();

                        //Delete Files added by Feature
                        for (int i = 0; i < currentWeb.RootFolder.Files.Count - 1; i++)
                        {
                            if (currentWeb.RootFolder.Files[i].Name.ToLower().Contains("overwrites"))
                            {
                                currentWeb.RootFolder.Files[i].Delete();
                                continue;
                            }
                            if (currentWeb.RootFolder.Files[i].Name.ToLower().Contains("BackupOfPerson"))
                            {
                                currentWeb.RootFolder.Files[i].Delete();
                                continue;
                            }
                            if (currentWeb.RootFolder.Files[i].Name.ToLower().Contains("CustomPerson"))
                            {
                                currentWeb.RootFolder.Files[i].Delete();
                                continue;
                            }
                        }

                        //Delete custom Webparts added by feature
                        SPList spList = currentWeb.Lists["Web Part Gallery"];
                        if (spList.RootFolder.Files["Follow Me.webpart"] != null)
                        {
                            spList.RootFolder.Files["Follow Me.webpart"].Delete();
                            spList.Update();
                        }
                    }

                    ////Reset PartCheck property: Property that flags the pages for the addition of the custom webparts the first time the page is visited)
                    //if (currentWeb.Properties[KEY_CHK] != null)
                    //    currentWeb.Properties.Remove(KEY_CHK);

                    #endregion
                    eventlog.WriteEntry("Successfull De-Activation of the MySiteHost Customization Feature: SiteUrl:" + currentWeb.Url);
                    logService.WriteTrace(100, logCategory_Information, TraceSeverity.Verbose, "Feature deactivated.", null);
                }
                catch (Exception e)
                {
                    logService.WriteTrace(100, logCategory_Error, TraceSeverity.High,
                      String.Format("Feature failed to deactivate. Exception message: {0} \r\n Stack Trace: \r\n {1}", new object[] { e.Message, e.StackTrace }), null);

                    eventlog.WriteEntry(String.Format("Error de-activating MySite Host Customization feature {0} :  SiteUrl:" + currentWeb.Url, e.ToString()), EventLogEntryType.Error);
                }
                finally
                {
                    currentWeb.Update();
                    currentWeb.AllowUnsafeUpdates = false;
                    mySiteHost.AllowUnsafeUpdates = false;
                }
                //}
            });
        }
    }
}
